package org.JDBC;

// 添加必要的导入语句
import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.junit.Test;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class DruidTest {

    //使遍历配置文件druid.properties内容
    @Test
    public void test_outProperties() {
        Properties properties = new Properties();
        InputStream is =
                ConnectionTest.class.getClassLoader().getResourceAsStream("druid.properties");
        try {
            properties.load(is);
            properties.forEach((k,v)->System.out.println(k +
                    ": " + v));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //获取druid连接对象
    @Test
    public void test_druid() {
        Connection conn = null;
        try {
//1.加载配置文件
            Properties properties = new Properties();
            InputStream is =
                    ConnectionTest.class.getClassLoader().getResourceAsStream("druid.properties");
            properties.load(is);
//2.获取连接池对象
            DataSource dataSource =
                    DruidDataSourceFactory.createDataSource(properties);
//3.获取连接
            conn = dataSource.getConnection();
            System.out.println("conn: " + conn);
//后续操作，跟以往相同，省略...
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}